package com.oxygen.pt.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oxygen.pt.pojo.dto.OxygenChamberInspectionSaveDTO;
import com.oxygen.pt.pojo.entity.MaintenanceDailyExcel;
import com.oxygen.pt.pojo.vo.InspectionSimpleVO;
import com.oxygen.pt.pojo.vo.OxygenChamberInspectionPageVO;
import com.oxygen.pt.pojo.vo.Result;
import com.oxygen.pt.service.OxygenChamberInspectionService;
import com.oxygen.pt.utils.exportUtils.MaintenanceExportUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@RestController()
@RequestMapping("/chamber-inspection")
@Slf4j
public class OxygenChamberInspectionController {

    @Resource
    private OxygenChamberInspectionService inspectionService;

    /**
     * 日检记录存储功能
     * @param dto 存储的DTO
     * @return  返回添加的结果
     * @throws JsonProcessingException JSON字符串序列化结果
     */
    @PostMapping("/save")
    public Result<String> create(@RequestBody OxygenChamberInspectionSaveDTO dto) throws JsonProcessingException {
        boolean saved = inspectionService.save(dto);
        if (saved)
            return Result.success("添加成功");
        return Result.error("添加失败");
    }

    /**
     * 删除日检报告
     * @param id 日检报告id
     * @return 返回删除的结果
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteById(@PathVariable Long id){
        boolean isDelete = inspectionService.deleteById(id);
        if (isDelete){
            return Result.success("删除成功");
        }else {
            return Result.error("删除失败");
        }
    }

    /**
     * 获取日检报告详情
     * @param id 日检报告id
     * @return OxygenChamberInspectionSaveDTO
     */
    @GetMapping("/{id}")
    public Result<OxygenChamberInspectionSaveDTO> getById(@PathVariable Long id) {
        OxygenChamberInspectionSaveDTO record = inspectionService.findById(id);
        return record != null ? Result.success(record)
                : Result.error("没有找到该报告");
    }

    /*
    日期范围的分页查询
     */
    @GetMapping("/page")
    public Result<PageInfo<OxygenChamberInspectionPageVO>> page(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate start,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate end,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        PageHelper.startPage(page, size);
        List<OxygenChamberInspectionPageVO> list = inspectionService.pageByDateRange(start, end);
        PageInfo<OxygenChamberInspectionPageVO> pageInfo = new PageInfo<>(list);
        return Result.success(pageInfo);
    }

    @PutMapping("/{id}")
    public Result<String> update(@PathVariable Long id,
                                 @RequestBody OxygenChamberInspectionSaveDTO dto) throws JsonProcessingException {
        boolean success = inspectionService.update(dto, id);
        return success ? Result.success("更新成功") : Result.error("更新失败");
    }


    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 1. 从数据库查出原始数据
        // TODO 应该选择下载哪一个月份的月度检查报告
        List<InspectionSimpleVO> dbList = inspectionService.listAllForExport();

        // 2. 转换为目标 Excel 模型
        List<MaintenanceDailyExcel> excelList = dbList.stream()
                .map(vo -> {
                    MaintenanceDailyExcel e = new MaintenanceDailyExcel();
                    e.setTime(vo.getInspectDate().toString());
                    e.setPowerSupply(statusToSymbol(vo.getPowerSupply()));
                    e.setComputerSystem(statusToSymbol(vo.getComputerSystem()));
                    e.setLightingSystem(statusToSymbol(vo.getLightingSystem()));
                    e.setOxygenDevice(statusToSymbol(vo.getOxygenDevice()));
                    e.setMeterStatus(statusToSymbol(vo.getMeterStatus()));
                    e.setFlowSwitch(statusToSymbol(vo.getFlowSwitch()));
                    e.setElectricParts(statusToSymbol(vo.getElectricParts()));
                    e.setSignature(vo.getInspector());   // 如需独立签字列可自行扩展
                    return e;
                })
                .collect(Collectors.toList());
        // 3. 导出
        MaintenanceExportUtil.export(response, excelList);
    }
    /**
     * 把 0/1 状态转成 √ / ×
     */
    private String statusToSymbol(Byte status) {
        return status != null && status == 0 ? "√" : "×";
    }






}